package com.ruoyi.core.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.core.domain.bo.MsgReplyRuleBo;
import com.ruoyi.core.domain.vo.MsgReplyRuleVo;
import com.ruoyi.core.domain.MsgReplyRule;
import com.ruoyi.core.mapper.MsgReplyRuleMapper;
import com.ruoyi.core.service.IMsgReplyRuleService;

import java.time.LocalTime;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 自动回复规则Service业务层处理
 *
 * @author ztx
 * @date 2023-04-10
 */
@RequiredArgsConstructor
@Service
public class MsgReplyRuleServiceImpl implements IMsgReplyRuleService {

    private final MsgReplyRuleMapper baseMapper;

    /**
     * 查询自动回复规则
     */
    @Override
    public MsgReplyRuleVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询自动回复规则列表
     */
    @Override
    public TableDataInfo<MsgReplyRuleVo> queryPageList(MsgReplyRuleBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<MsgReplyRule> lqw = buildQueryWrapper(bo);
        Page<MsgReplyRuleVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询自动回复规则列表
     */
    @Override
    public List<MsgReplyRuleVo> queryList(MsgReplyRuleBo bo) {
        LambdaQueryWrapper<MsgReplyRule> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<MsgReplyRule> buildQueryWrapper(MsgReplyRuleBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<MsgReplyRule> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getAppid()), MsgReplyRule::getAppid, bo.getAppid());
        lqw.like(StringUtils.isNotBlank(bo.getRuleName()), MsgReplyRule::getRuleName, bo.getRuleName());
        lqw.eq(StringUtils.isNotBlank(bo.getMatchValue()), MsgReplyRule::getMatchValue, bo.getMatchValue());
        lqw.eq(bo.getExactMatch() != null, MsgReplyRule::getExactMatch, bo.getExactMatch());
        lqw.eq(StringUtils.isNotBlank(bo.getReplyType()), MsgReplyRule::getReplyType, bo.getReplyType());
        lqw.eq(StringUtils.isNotBlank(bo.getReplyContent()), MsgReplyRule::getReplyContent, bo.getReplyContent());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), MsgReplyRule::getStatus, bo.getStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getDescription()), MsgReplyRule::getDescription, bo.getDescription());
        lqw.eq(bo.getEffectTimeStart() != null, MsgReplyRule::getEffectTimeStart, bo.getEffectTimeStart());
        lqw.eq(bo.getEffectTimeEnd() != null, MsgReplyRule::getEffectTimeEnd, bo.getEffectTimeEnd());
        lqw.eq(StringUtils.isNotBlank(bo.getPriority()), MsgReplyRule::getPriority, bo.getPriority());
        return lqw;
    }

    /**
     * 新增自动回复规则
     */
    @Override
    public Boolean insertByBo(MsgReplyRuleBo bo) {
        MsgReplyRule add = BeanUtil.toBean(bo, MsgReplyRule.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改自动回复规则
     */
    @Override
    public Boolean updateByBo(MsgReplyRuleBo bo) {
        MsgReplyRule update = BeanUtil.toBean(bo, MsgReplyRule.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(MsgReplyRule entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除自动回复规则
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
    public List<MsgReplyRule> getValidRules() {
        return baseMapper.selectList(
            new QueryWrapper<MsgReplyRule>()
                .eq("status", 1)
                .isNotNull("match_value")
                .ne("match_value", "")
                .orderByDesc("priority"));
    }
    @Override
    public List<MsgReplyRule> getMatchedRules(String appid, boolean exactMatch, String keywords) {
        LocalTime now = LocalTime.now();
        return this.getValidRules().stream()
            .filter(rule->!org.springframework.util.StringUtils.hasText(rule.getAppid()) || appid.equals(rule.getAppid())) // 检测是否是对应公众号的规则，如果appid为空则为通用规则
            .filter(rule->null == rule.getEffectTimeStart() || rule.getEffectTimeStart().toLocalTime().isBefore(now))// 检测是否在有效时段，effectTimeStart为null则一直有效
            .filter(rule->null == rule.getEffectTimeEnd() || rule.getEffectTimeEnd().toLocalTime().isAfter(now)) // 检测是否在有效时段，effectTimeEnd为null则一直有效
            .filter(rule->isMatch(exactMatch || rule.getExactMatch() == 1,rule.getMatchValue().split(","),keywords)) //检测是否符合匹配规则
            .collect(Collectors.toList());
    }
    public static boolean isMatch(boolean exactMatch, String[] ruleWords, String checkWords) {
        if (!org.springframework.util.StringUtils.hasText(checkWords)) {
            return false;
        }
        for (String words : ruleWords) {
            if (exactMatch && words.equals(checkWords)) {
                return true;//精确匹配，需关键词与规则词语一致
            }
            if (!exactMatch && checkWords.contains(words)) {
                return true;//模糊匹配
            }
        }
        return false;
    }
}
